package com.city.parking;

import java.util.HashMap;
import java.util.Random;

import org.json.JSONException;
import org.json.JSONObject;

import com.city.parking.util.HttpClientUtil;
import com.city.parking.util.HttpRequest;
import com.city.parking.util.HttpResult;
import com.city.parking.util.SharePrefUtil;
import com.city.parking.util.Utils;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.View;
import android.widget.Toast;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.gui.CommonDialog;
import cn.smssdk.gui.RegisterPage;

public class UserRegister implements Callback {
	private boolean ready;
	private Context mContext;
	private Dialog pd;
	private String phone, uid;
	private Handler mCallback = null;
	
	private final int MSG_PARKING_SERVER = 1;
	
	public static final int MSG_USER_REGISTER = 1;
	public static final int USER_REGISTER_SUCCESS = 1;
	public static final int USER_REGISTER_FAILED = 2;

	// 短信注册，随机产生头像
	private static final String[] AVATARS = {
		"http://tupian.qqjay.com/u/2011/0729/e755c434c91fed9f6f73152731788cb3.jpg",
		"http://99touxiang.com/public/upload/nvsheng/125/27-011820_433.jpg",
		"http://img1.touxiang.cn/uploads/allimg/111029/2330264224-36.png",
		"http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339485237265.jpg",
		"http://diy.qqjay.com/u/files/2012/0523/f466c38e1c6c99ee2d6cd7746207a97a.jpg",
		"http://img1.touxiang.cn/uploads/20121224/24-054837_708.jpg",
		"http://img1.touxiang.cn/uploads/20121212/12-060125_658.jpg",
		"http://img1.touxiang.cn/uploads/20130608/08-054059_703.jpg",
		"http://diy.qqjay.com/u2/2013/0422/fadc08459b1ef5fc1ea6b5b8d22e44b4.jpg",
		"http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339510584349.jpg",
		"http://img1.touxiang.cn/uploads/20130515/15-080722_514.jpg",
		"http://diy.qqjay.com/u2/2013/0401/4355c29b30d295b26da6f242a65bcaad.jpg"
	};
	
	// 弹出加载框
	private void showDialog(){
		if (pd != null && pd.isShowing()) {
			pd.dismiss();
		}
		pd = CommonDialog.ProgressDialog(mContext);
		pd.show();
	}

	protected void onDestroy() {
		if (ready) {
			// 销毁回调监听接口
			SMSSDK.unregisterAllEventHandler();
		}
		if (pd != null && pd.isShowing()) {
			pd.dismiss();
		}
	}
	
	public UserRegister(Context ctx, Handler cbk) {		
		mContext = ctx;
		mCallback = cbk;
		SMSSDK.initSDK(ctx, ParkingApp.APPKEY, ParkingApp.APPSECRET);
		final Handler handler = new Handler(this);
		EventHandler eventHandler = new EventHandler() {
			public void afterEvent(int event, int result, Object data) {
				Message msg = new Message();
				msg.arg1 = event;
				msg.arg2 = result;
				msg.obj = data;
				handler.sendMessage(msg);
			}
		};
		// 注册回调监听接口
		SMSSDK.registerEventHandler(eventHandler);
		ready = true;

		// 获取新好友个数
		SMSSDK.getNewFriendsCount();
	}
	
	private void registerUser(String country, String phone) {
		Random rnd = new Random();
		int id = Math.abs(rnd.nextInt());
		uid = String.valueOf(id);
		String nickName = "CityPark_u" + uid;
		String avatar = AVATARS[id % 12];
		SMSSDK.submitUserInfo(uid, nickName, avatar, country, phone);

		final Handler handler = new Handler(this);
		JSONObject json = new JSONObject();
		try {
			json.put("userName", nickName);
			json.put("number", phone);
			String seed = System.currentTimeMillis() + "";
			json.put("passwd", Utils.md5(seed.getBytes()));
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		HttpRequest req = new HttpRequest(ParkingApp.url_insert_user, MSG_PARKING_SERVER, json.toString(), handler);
		HttpClientUtil.post(req);
	}
    
    public void launchRegisterPage() {
		showDialog();

		RegisterPage registerPage = new RegisterPage();
		registerPage.setRegisterCallback(new EventHandler() {
			public void afterEvent(int event, int result, Object data) {
				// 解析注册结果
				if (result == SMSSDK.RESULT_COMPLETE) {
					@SuppressWarnings("unchecked")
					HashMap<String,Object> phoneMap = (HashMap<String, Object>) data;
					String country = (String) phoneMap.get("country");
					phone = (String) phoneMap.get("phone");
					// 提交用户信息
					registerUser(country, phone);
				}
			}
		});
		registerPage.show(mContext);
    }

	// 更新，新好友个数
	private void refreshViewCount(Object data){
		int newFriendsCount = 0;
		try {
			newFriendsCount = Integer.parseInt(String.valueOf(data));
		} catch (Throwable t) {
			newFriendsCount = 0;
		}
		if (pd != null && pd.isShowing()) {
			pd.dismiss();
		}
	}
	
	@Override
    public boolean handleMessage(Message msg) {
	    // TODO Auto-generated method stub
		if (pd != null && pd.isShowing()) {
			pd.dismiss();
		}
		
		if (msg.what == MSG_PARKING_SERVER) {
			int arg = USER_REGISTER_FAILED;
			HttpResult ret = (HttpResult)msg.obj;
			if( msg.arg1 == HttpRequest.NET_SUCCESS  &&  ret != null && ret.status != HttpResult.STATUS_FAILED) {
				SharePrefUtil.setUsrId(ret.id+"");
				SharePrefUtil.setPhone(phone);
				ParkingApp.mUid = ret. id;
				ParkingApp.mPhone = phone;
				Utils.log("注册成功 " + ret.msg + ", status=" + ret.status);
				Toast.makeText(ParkingApp.get(), "注册成功", Toast.LENGTH_SHORT).show();
				arg = USER_REGISTER_SUCCESS;
			} else {
				Utils.log("注册失败，请检查网络后重试");
				Toast.makeText(ParkingApp.get(), "注册失败，请检查网络后重试", Toast.LENGTH_SHORT).show();
			}
			if (mCallback != null) {
				Message message = mCallback.obtainMessage();
				message.what = MSG_USER_REGISTER;
				message.arg1 = arg;
				mCallback.sendMessage(message);
			}
			return false;
		}

		int event = msg.arg1;
		int result = msg.arg2;
		Object data = msg.obj;
		if (event == SMSSDK.EVENT_SUBMIT_USER_INFO) {
			// 短信注册成功后，返回MainActivity,然后提示新好友
			if (result == SMSSDK.RESULT_COMPLETE) {
				Utils.log("手机验证成功");
			} else {
				((Throwable) data).printStackTrace();
			}
		} else if (event == SMSSDK.EVENT_GET_NEW_FRIENDS_COUNT){
			if (result == SMSSDK.RESULT_COMPLETE) {
				refreshViewCount(data);
			} else {
				((Throwable) data).printStackTrace();
			}
		}
		return false;
    }
}
